<?php
namespace app\api\controller;

use think\facade\Request;
use think\Db;
use think\Controller;

class Base extends Controller
{
    public $user_id;
    public $token;
    public $requests;
    function __construct()
    {
        $request = Request::instance();
        $this->requests = $request;
        $token = $request->header('token');
       
         
        if (!isset($token) || $token=="" ){
            self::return_err_json(1001);
        }
        $this->token = $token;
        $this->user_id = self::checkToken($token);
        $this->s_id = config('app.s_id');
    }

    /**
     * 检查token
     * @param $token
     */
    private static function checkToken($token)
    {
        $result = Db::name("user_token")->where(['token'=>$token])->find();
        if( empty($result) ) self::return_err_json(1002);
        $time = time();
        if( $result['expire_time'] < $time ) self::return_err_json(1003);
        if( ($result['expire_time']-$time) < 60*60*24*3 ){
            Db::name("user_token")->where(['user_id'=>$user_id])->update(["expire_time"=>$time+60*60*24*7,'update_time'=>time()]);
        }
        return $result['user_id'];
    }
    /**
     * 构建返回数据 函数
     * @param $errorCode  错误码
     * @param string $data  返回的数据
     * @return false|string
     */
    public static function return_err_json($errorCode, $data="")
    {
        $returnData['code'] = $errorCode;
        $returnData['data'] = $data;
        $returnData['msg'] = self::getErrorMsg($errorCode);
        exit(json_encode($returnData,JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取错误信息
     * @param $number 错误码
     * @return mixed
     */
    public static function getErrorMsg($number)
    {
        $errArr = [
            1 => "success",
            1001 => "缺少参数token！",
            1002 => "参数token错误！",
            1003 => "token已过期，请重新获取token！",
            //1004 => "token错误！",
        ];
        return $errArr[$number];
    }
}